package com.maikang.exammall.handler;

import com.maikang.exammall.builder.TextBuilder;
import com.maikang.exammall.entity.User;
import com.maikang.exammall.repository.UserRepository;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Log4j2
public class SubscribeHandler extends AbstractHandler {
    private final static String greetings = "Hello， 感谢您关注迈康体检， 我们时刻关注您的健康。\n<a href='https://www.mkhealth.club/'>点次选购体检套餐和预约体检</a>\n\n客服热线：0668-2853837";

    @Autowired
    private UserRepository userRepository;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {

        log.info("新关注用户 OPENID: " + wxMessage.getFromUser());

        // 获取微信用户基本信息
        try {
            WxMpUser userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser(), null);
            if (userWxInfo != null) {
                // save the subscribe user to database if not exists.
                User user = userRepository.findByOpenId(userWxInfo.getOpenId()).orElse(null);
                if (user == null) {
                    log.info("user {}:{} does not exist, saving to database", userWxInfo.getNickname(), userWxInfo.getOpenId());
                    user = User.builder().city(userWxInfo.getCity())
                            .province(userWxInfo.getCountry())
                            .username(userWxInfo.getNickname())
                            .avatarUrl(userWxInfo.getHeadImgUrl())
                            .gender(userWxInfo.getSex())
                            .openId(userWxInfo.getOpenId())
                            .unionId(userWxInfo.getUnionId())
                            .build();
                    // user comes from scanning Qrcode
                    if (wxMessage.getEvent().equalsIgnoreCase("subscribe")) {
                        String eventKey = wxMessage.getEventKey();
                        log.info("got subscribe sceneValue {}", eventKey);
                        if (eventKey.startsWith("qrscene_")) {
                            String sceneId = eventKey.replace("qrscene_", "");
                            user.setRefererId(Long.valueOf(sceneId));
                            user.setOriginalRefererId(Long.valueOf(sceneId));
                        }
                    }
                } else {
                    user.setUnsubscribed(false);
                    user.setUnionId(userWxInfo.getUnionId());
                }
                userRepository.save(user);
            }
        } catch (WxErrorException e) {
            if (e.getError().getErrorCode() == 48001) {
                log.info("该公众号没有获取用户信息权限！");
            }
        }


        WxMpXmlOutMessage responseResult = null;
        try {
            responseResult = this.handleSpecial(wxMessage);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        if (responseResult != null) {
            return responseResult;
        }

        try {
            return new TextBuilder().build(greetings, wxMessage, weixinService);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage) throws Exception {

        //TODO
        return null;
    }

}
